package com.itheima.stock.Thread;

/*
    void wait()	导致当前线程等待，直到另一个线程调用该对象的 notify()方法或 notifyAll()方法
    void notify()	唤醒正在等待对象监视器的单个线程
    void notifyAll()	唤醒正在等待对象监视器的所有线程

 */
public class Wait_Notify {
    public static void main(String[] args) {
        new Thread(new Customer()).start();
        new Thread(new Producer()).start();


    }
    // 生产者
    public static class Producer implements Runnable {
        @Override
        public void run() {
            while (true){
                synchronized (Warehouse.class){
                    if (Warehouse.PRODUCT_NUM == 0){
                        System.out.println("产品卖完了");
                        break;
                    }
                    if (Warehouse.isEmpty){
                        Warehouse.isEmpty = false;
                        System.out.println("生产者生产了一个产品");
                        Warehouse.class.notifyAll();
                    }else { // 仓库有货就等消费者用完
                        try {
                            Warehouse.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    // 消费者
    public static class Customer implements Runnable {
        @Override
        public void run() {
            while (true){
                synchronized (Warehouse.class){
                    if (Warehouse.PRODUCT_NUM == 0){
                        break;
                    }
                    if (!Warehouse.isEmpty){
                        Warehouse.PRODUCT_NUM--;
                        Warehouse.isEmpty = true;
                        System.out.println("消费者消费了一个产品，剩余产品数为：" + Warehouse.PRODUCT_NUM);
                        Warehouse.class.notifyAll();
                    }else { // 仓库没货就等生产者生产
                        try {
                            Warehouse.class.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    // 信号量
    public static class Warehouse {
        private static int PRODUCT_NUM = 100;// 产品数
        private static boolean isEmpty = true; // 仓库是否为空

    }
}
